#!/usr/bin/python

import sys,getopt
import commands
import calendar
import re
import os
import time

import JoDef

import datetime
from dateutil.relativedelta import *
from dateutil.parser import *
from dateutil.tz import *
from optparse import OptionParser

import pdb

def is_date(str):
	"""return True if str is a valid date; False otherwise.
	"""

	try:
		parse(str,fuzzy=False)
		return True
	except ValueError:
		return False

def parse_date(str):
	try:
		return parse(str,fuzzy=True)
	except ValueError:
		raise

def date_range(date=None,range=None,hour=None):
	date1 = datetime.datetime.now()
	date2 = date1+relativedelta(days=-1)
	if date:
		try:
			date1 = parse(date,fuzzy=True)
		except:
			pass

	if not range:
		range = JoDef.JOPREF_DFLTRANGE
	if range.lower() == 'daily':
		if date and relativedelta(datetime.datetime.now(),date1).day <= 0:
			date1 = date1+relativedelta(weeks=-1)
			date2 = date1+relativedelta(days=-1)
	elif range.lower() == 'weekly':
		date2 = date1+relativedelta(weeks=-1)
	elif range.lower() == 'biweekly':
		date2 = date1+relativedelta(weeks=-2)
	elif range.lower() == 'monthly':
		date2 = date1+relativedelta(months=-1)
	elif range.lower() == 'quarterly':
		date2 = date1+relativedelta(months=-3)
	elif range.lower() == 'yearly':
		date2 = date1+relativedelta(years=-1)

	if hour:
		date1 = date1+relativedelta(hour=hour,minute=0,second=0,microsecond=0)
		date2 = date2+relativedelta(hour=hour,minute=0,second=0,microsecond=0)
	return (time.mktime(date2.timetuple()),time.mktime(date1.timetuple()))
	
def print_time(et):
	dfmt = "%a %b %d, %Y %l%P"
	return time.strftime(dfmt,time.localtime(et))


def main(argv):
	usage = "usage: %prog [options] datestr"
	parser = OptionParser(usage)
	parser.add_option("-t","--type",dest="type",help="type of report to create, options include daily, weekly, biweekly and monthly",default="daily")
	parser.add_option("-c","--clock",dest="clock",help="the hour of the day to use in date ranges, use 24 hour clock")

	(options,args) = parser.parse_args()

	datestr = ''
	range = None 
	hour = None
	if len(args) > 0:
		datestr = args[0]
	if options.type:
		range = options.type
	print is_date(datestr)
	print parse_date(datestr)
	if options.clock:
		hour = int(options.clock)

	if range:
		print range
		for i in date_range(datestr,range,hour):
			print_time(i)
		
if __name__ == "__main__":
    main(sys.argv[1:])
